package com.alex.tinyurl.controller;

import com.alex.tinyurl.Tools;
import com.alex.tinyurl.api.ITinyUrl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

@RestController
@RequestMapping("/turl")
public class TinyUrlController {

    private final static Logger LOG = LoggerFactory.getLogger(TinyUrlController.class);
    public static final String FIX_PREFIX = "http://turl.com:8080/turl/r?tinyUrl=";

    @Resource
    private ITinyUrl tinyUrlService;

    /**
     * 生成短URL
     *
     * @param originalUrl 原始URL
     * @return 返回新的短URL
     */
    @RequestMapping(value = "/s", method = RequestMethod.POST)
    String genUrl(String originalUrl) {
        LOG.info("[origin url:{}]", originalUrl);
        String tinyUrl = tinyUrlService.genUrl(originalUrl);
        LOG.info("[tiny url:{}]", tinyUrl);
        return FIX_PREFIX + tinyUrl;
    }

    /**
     * 通过短URL跳转到原始URL
     *
     * @param tinyUrl 短URL
     * @return 跳转到原始URL，格式"redirect://"
     */
    @RequestMapping(value = "/r", method = RequestMethod.GET)
    ModelAndView redirect(String tinyUrl) {
        LOG.info("[visit tiny url:{}]", tinyUrl);
        String originalUrl = tinyUrlService.getOriginalUrl(tinyUrl);
        String redirectUrl = Tools.redirectUrl(originalUrl);
        LOG.info("[redirect url:{}]", redirectUrl);
        return new ModelAndView(redirectUrl);
    }


}
